package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.ServerDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.ServerDaoImpl;
import com.atguigu.pojo.Page;
import com.atguigu.pojo.Server;
import com.atguigu.service.ServerService;
import com.atguigu.utils.WebUtils;

import java.util.List;

public class ServerServiceImpl implements ServerService {
    ServerDao serverDao=new ServerDaoImpl();//这里面是sql,接受参数,组织sql,执行mysql查询;所以它是公共的的类,增删改查就用它的方法实现
    @Override
    public void addServer(Server server) {
        serverDao.addServer(server);
    }

    @Override
    public void updateServer(Server server) {
        String newFreePorts= WebUtils.getFreePorts(server.getPorts());
        //System.out.println("server.getPorts()"+server.getPorts());
        //System.out.println("newFreePorts"+newFreePorts);
        server.setFreePorts(newFreePorts);
        serverDao.updateServer(server);
    }

    @Override
    public void deleteServerById(String id) {
        serverDao.deleteServerById(id);
    }

    @Override
    public Server queryServerById(String id) {
        Server server=serverDao.queryServerById(id);
        return server;
    }

    @Override
    public List<Server> queryServers() {
        List<Server> queryServers=serverDao.queryServers();
        return queryServers;
    }

    @Override
    public Page page(Integer pageNo, Integer pageSize) {
        Page<Server> page=new Page<>();
        page.setPagesize(pageSize);
        Integer pageTotalCount=serverDao.queryForPageTotalCount();
        page.setPageTotalCount(pageTotalCount);
        Integer pageTotal=pageTotalCount/pageSize;
        if(pageTotalCount % pageSize >0){
            pageTotal++;//总条数,除以一页条数,大于0,页码数+1
        }
        page.setPageTotal(pageTotal);
        System.out.println("pageNo 原来是 is:"+pageNo);
        if(pageNo<1){//防止用户输入量太大
            pageNo=1;
        }else if(pageNo>pageTotal){
            pageNo=pageTotal;
        }
        page.setPageNo(pageNo);//当前页码
        System.out.println("pageNo 现在是 is:"+pageNo);
        System.out.println("pageTotal is:"+pageTotal);
        //要得到的是page的items
        Integer begin=(page.getPageNo()-1)*pageSize;
        List<Server> items=serverDao.queryForPageItems(begin,pageSize);
        page.setItems(items);
        return page;
    }
}
